package cn.initcap.concurrency.concurrency.sync;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

/**
 * 这里需要注意，当此类为父类时，子类继承的方法时不会携带 synchronized ，必须子类重新声明
 *
 * @author initcap
 * @date Created in 2018/6/13 PM10:02.
 */
@Slf4j
public class SynchronizedExample1 {

    private static final int CLIENT_SIZE = 10;

    public static void main(String[] args) {
        SynchronizedExample1 example1 = new SynchronizedExample1();
        SynchronizedExample1 example2 = new SynchronizedExample1();
        ExecutorService executorService = new ThreadPoolExecutor(0, CLIENT_SIZE, 60L,
                TimeUnit.SECONDS, new SynchronousQueue<>(),
                new ThreadFactoryBuilder().setNameFormat("SynchronizedExample1").build());
        executorService.execute(() -> example1.test1(1));
        executorService.execute(() -> example2.test2(2));
    }

    /**
     * 修饰一个代码块,作用的对象是调用的对象，不同对象之间相互不影响
     */
    private void test1(int j) {
        synchronized (this) {
            for (int i = 0; i < CLIENT_SIZE; i++) {
                log.info("test1 {} - {}", j, i);
            }
        }
    }

    /**
     * 修饰一个方法,作用的对象是调用的对象，不同对象之间相互不影响
     */
    private synchronized void test2(int j) {
        for (int i = 0; i < CLIENT_SIZE; i++) {
            log.info("test2 {} - {}", j, i);
        }
    }

}
